package com.hyh.search.service.impl;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.hyh.search.Mapper.ProductMapper;
import com.hyh.search.domain.Complex.ProductComplex;
import com.hyh.search.result.PageResult;
import com.hyh.search.service.ProductService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RestHighLevelClient client;
    @Override
    public PageResult selectAllProduct() {
        return new PageResult(HttpStatus.HTTP_OK,productMapper.selectList(null),"查询成功" );
    }


    // 自动补全
    @Override
    public PageResult getSuggestion(String key) {
        SearchRequest request = new SearchRequest("product");
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "title_suggest",
                SuggestBuilders
                        .completionSuggestion("suggestion")
                        .prefix(key)
                        .skipDuplicates(true)
                        .size(10)
        ));
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Suggest suggest = response.getSuggest();
        List<String> list = new ArrayList<>();
        suggest.getSuggestion("title_suggest").forEach(suggestion -> {
            suggestion.getOptions().forEach(entry -> {
                list.add(entry.getText().string());
            });
        });
        return new PageResult(HttpStatus.HTTP_OK,list,"查询成功" );

    }

    // 根据词条查询商品
    @Override
    public PageResult search(String key,Integer page,Integer size) {
        SearchRequest searchRequest = new SearchRequest("product");
        searchRequest.source()
                .query(QueryBuilders.matchQuery("all", key))
                .from((page-1)*size).size(size)
                .highlighter(new HighlightBuilder().field("title").requireFieldMatch(false));
        return getPageResult(searchRequest);
    }

    // 获取全部的商品信息
    @Override
    public PageResult searchAll(Integer page, Integer size) {
        SearchRequest searchRequest = new SearchRequest("product");
        searchRequest.source()
                .query(QueryBuilders.matchAllQuery())
                .from((page-1)*size).size(size)
                .highlighter(new HighlightBuilder().field("title").requireFieldMatch(false));
        return getPageResult(searchRequest);
    }

    // 根据价格查询商品
    @Override
    public PageResult searchByPrice(String key, Integer page, Integer size, Integer min, Integer max) {
        SearchRequest searchRequest = new SearchRequest("product");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("all", key)));
        // 设置高亮
        sourceBuilder.highlighter(new HighlightBuilder()
                .field("title").requireFieldMatch(false));
        // 设置分页
        sourceBuilder.from((page - 1) * size).size(size);
        // 设置价格范围查询
        if (min != null && max != null) {
            sourceBuilder.query(QueryBuilders.rangeQuery("price")
                    .gte(min)
                    .lte(max));
        }

        searchRequest.source(sourceBuilder);

        return getPageResult(searchRequest);
    }

    //结果的解析方法
    private PageResult getPageResult(SearchRequest searchRequest) {
        List<ProductComplex> productComplexes = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        // 执行搜索
        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            // 将搜素结果返回
            SearchHits hits = searchResponse.getHits();
            hits.forEach(hit -> {
                ProductComplex productComplex = JSON.parseObject(hit.getSourceAsString(), ProductComplex.class);
                // 获取高亮的结果集
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!highlightFields.isEmpty()) {
                    HighlightField highlightField = highlightFields.get("title");
                    String title = highlightField.getFragments()[0].string();
                    productComplex.setTitle(title);
                }
                productComplexes.add(productComplex);
            });
            map.put("total", hits.getTotalHits().value);
            map.put("data", productComplexes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return new PageResult(HttpStatus.HTTP_OK, map, "查询成功");
    }
}
